<template>
  <div class="zlst-form--editor">
    <Layout>
      <editor-header
        :selectedIndex="selectedWidgetIndex"
        :echartDrag="echartDrag"
        :uiItemList="uiItemList"
        @preview="preview">
      </editor-header>
      <Content :class="{'widget-empty': uiItemList.length === 0}">
        <Form :label-position="formProperty.position" :label-width="formProperty.width">
          <draggable
            class="zlst-form-container"
            v-model="uiItemList"
            :options="{ group: 'widgets', ghostClass: 'ghost' }"
            @change="dragWidgetHandler"
          >
            <form-item-dispatcher
              v-for="item in uiItemList"
              :key="item.id"
              :setting="item"
              :editable="true"
              :selected="item.id === $store.getters['uiEditor/currentWidgetId']"
              :markSelect="markSelect"
            />
          </draggable>
        </Form>
      </Content>
    </Layout>
    <Sider width="300">
      <setting-panel :formProperty="formProperty" :setting="selectedWidget"/>
    </Sider>
    <preview-modal ref="previewModal" :formProperty="formProperty" :uiItemList="uiItemList" />
  </div>
</template>

<script>
import _ from 'lodash'
import Draggable from 'vuedraggable'
import uuidv4 from 'uuid/v4'
import { mapGetters } from 'vuex'
import FormItemDispatcher from './form-item-render/dispatcher'
import SettingPanel from './setting-panel'
import EditorHeader from './header/editor-header'
import PreviewModal from './modals/preview'
import { chartUtil, chartOptions } from '@/assets/js/graph-chart'

export default {
  name: 'MainBoard',
  components: {
    Draggable,
    FormItemDispatcher,
    SettingPanel,
    EditorHeader,
    PreviewModal
  },
  data () {
    return {
      formProperty: {
        position: 'left',
        width: 100
      },
      uiItemList: [],
      selectedWidgetIndex: -1,    // 当前选中组件的索引值
      selectedWidgetHistory: [],   // 操作组件的历史记录
      echartDrag: {},               // 图表拖拽对象
      componentList: [],        // 选中的组件集
      markSelect: false,
    }
  },
  computed: {
    selectedWidget () {
      return this.findWidgetById(this['uiEditor/currentWidgetId'])
    },
    ...mapGetters(['uiEditor/currentWidgetId'])
  },
  methods: {
    // Vue.draggable 操作事件
    // 文档请参看 https://github.com/SortableJS/Vue.Draggable
    dragWidgetHandler (evt) {
      const type = Object.keys(evt)[0]
      switch (type) {
        case 'added':
          this.addWidget(evt[type].element.id)
          break
        case 'moved':
          this.moveWidget(evt[type].element.id)
          break
      }
    },
    selectWiget (id) {
      if (this['uiEditor/currentWidgetId'] === id) {
        return
      }
      this.$store.commit('uiEditor/setCurrentWigetId', id)
      this.selectedWidgetHistory.push(this.findWidgetById(id))
    },
    addWidget (id) {
      this.$store.commit('uiEditor/setCurrentWigetId', id)
      this.selectedWidgetHistory.push(this.findWidgetById(id))
    },
    moveWidget (id) {
      this.$store.commit('uiEditor/setCurrentWigetId', id)
      this.selectedWidgetHistory.push(this.findWidgetById(id))
    },
    // 复制表单项
    copyWidget (id) {
      let { self, index, siblings } = this.findSiblingsById(id)
      const clone = _.cloneDeep(self)
      clone.id = uuidv4()
      siblings.splice(index + 1, 0, clone)
      this.$store.commit('uiEditor/setCurrentWigetId', clone.id)
      this.selectedWidgetHistory.push(clone)
    },
    // 删除表单项
    deleteWidget (id) {
      let { self, index, siblings } = this.findSiblingsById(id)
      siblings.splice(index, 1)
      let deleteWidgets = []
      if (self.type === 'grid') {
        let columns = []
        self.options.columns.forEach(column => columns.push(...column.list))
        deleteWidgets = [self, ...columns]
      } else {
        deleteWidgets = [self]
      }
      // 将已删除的选项从历史记录中删除掉
      this.selectedWidgetHistory = this.selectedWidgetHistory.filter(item => {
        return !deleteWidgets.includes(item)
      })
      let length = this.selectedWidgetHistory.length
      if (length > 0) {
        this.$store.commit('uiEditor/setCurrentWigetId', this.selectedWidgetHistory[length - 1].id)
      } else {
        this.$store.commit('uiEditor/setCurrentWigetId', undefined)
      }
    },
    findWidgetById (id) {
      let widget
      this.uiItemList.some(item => {
        if (item.id === id) {
          widget = item
          return true
        } else if (item.type === 'grid') {
          item.options.columns.some(el => {
            return el.list.some(e => {
              if (e.id === id) {
                widget = e
                return true
              }
            })
          })
        }
      })
      return widget
    },
    findSiblingsById (id) {
      let self
      let siblings = []
      let index = -1
      this.uiItemList.some((item, i) => {
        if (item.id === id) {
          siblings = this.uiItemList
          self = item
          index = i
          return true
        } else if (item.type === 'grid') {
          item.options.columns.some(el => {
            return el.list.some((e, j) => {
              if (e.id === id) {
                siblings = el.list
                self = e
                index = j
                return true
              }
            })
          })
        }
      })
      return { self, index, siblings }
    },
    fieldPropertyUpdate (id, key, value) {
      let widget = this.findWidgetById(id)
      widget.options[key] = value
    },
    formPropertyUpdate (val) {
      this.formProperty = val
    },
    buttonAssociationHandler (key, value) {
      console.log(key,value)
      console.log('表单',this.uiItemList)
    },
    // 数据源开始拖拽
    widgetDataStart(item) {
      this.echartDrag = item
    },
    // 图形属性改变触发
    widgetChart(chartInfo) {
      console.log('triggerByChart______')
      console.log(JSON.stringify(chartInfo.graphOptions))
      const sourceWidget = this.selectedWidget
      sourceWidget.graphOptions = chartInfo.graphOptions
      sourceWidget.isBegin = false
      sourceWidget.graphType = chartInfo.graphInfo.type
      sourceWidget.supportTypes = chartInfo.graphInfo.supportTypes
      sourceWidget.dataSource = chartInfo.dataSource
    },
    preview () {
      this.$refs.previewModal.open()
    },
    markSelectAdd(value) {
      // 选中 添加
      this.componentList.push(this.uiItemList[value])
      console.log(this.componentList)
    },
    markSelectDelete(value) {
      // 不选择 删除
      console.log(this.componentList)
    },
    AComponentSelected(value, index) {
      this.markSelect = value
      if(!value){
        this.uiItemList[this.selectedWidgetIndex].options.event[index].value = this.componentList
      }
    }
  },
  mounted () {
    this.$on('field-property-changed', this.fieldPropertyUpdate)
    this.$on('field-query-handler', this.formPropertyQuery)
    this.$on('widget-selected', this.selectWiget)
    this.$on('widget-copy', this.copyWidget)
    this.$on('widget-delete', this.deleteWidget)
    this.$on('widget-data-start', this.widgetDataStart)
    this.$on('field-query-handler', this.formPropertyQuery)
    this.$on('widget-chart', this.widgetChart)
    this.$on('form-property-changed', this.formPropertyUpdate)
    this.$on('button-association-handler', this.buttonAssociationHandler)
    this.$on('markSelect-add', this.markSelectAdd)
    this.$on('markSelect-delete', this.markSelectDelete)
    this.$on('AComponent-selected', this.AComponentSelected)
  }
}
</script>
